package com.gitee.srurl.core.util.redis;

import com.gitee.srurl.core.util.SpringContextUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDeque;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @date 2023/4/29 19:52
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class RedisListUtil<T> {
    private static final RedissonClient redissonClient = SpringContextUtil.getBean(RedissonClient.class);

    public static <T> int lPush(String key, T... data) {

        RDeque<T> deque = redissonClient.getDeque(key);
        return deque.addFirst(data);
    }

    public static <T> List<T> lRange(String key) {

        RList<T> list = redissonClient.getList(key);
        return list.readAll();
    }

    public static <T> boolean remove(String key, T data) {

        RDeque<T> deque = redissonClient.getDeque(key);
        return deque.remove(data);
    }

    public static <T> T bRPopLPush(String key, String backupKey) {

        RBlockingQueue<T> blockingQueue = redissonClient.getBlockingQueue(key);
        return blockingQueue.pollLastAndOfferFirstTo(backupKey);
    }

    public static <T> T bRPopLPush(String key, String backupKey, long time, TimeUnit timeUnit) {

        RBlockingQueue<T> blockingQueue = redissonClient.getBlockingQueue(key);
        try {
            return blockingQueue.pollLastAndOfferFirstTo(backupKey, time, timeUnit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }
    }
}
